package practise;

import com.mysql.jdbc.Driver;

import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

public class Demo01_DriverManager {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            // 加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 建立连接
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/java113?characterEncoding=utf8" +
                    "&allowPublicKeyRetrieval=true&useSSL=false", "root", "123456");
            // 获取执行SQL 的对象
            statement = connection.createStatement();
            // 执行SQL 操作
            Scanner in = new Scanner(System.in);
            System.out.println("请输入名字");
            String name = in.nextLine();
            // 这个方法是不安全的 例如' or 1 = 1; #
            String sql = "select student_id, sn, name, mail, class_id from student where name = '" + name + "'";
            // 查询结果
            resultSet = statement.executeQuery(sql);
            // 打印
            while (resultSet.next()) {
                long stuId = resultSet.getLong(1);
                String sn = resultSet.getString(2);
                String uname = resultSet.getString(3);
                String mail = resultSet.getString(4);
                long classId = resultSet.getLong(5);
                System.out.println(MessageFormat.format("学生id={0}, 学生学号={1}, 学生姓名={2}, 学生邮箱={3}, 班级id={4}", stuId, sn, uname, mail, classId));
            }
        } catch (ClassNotFoundException | SQLException e) {
            System.out.println(e);
        } finally {
            // 关闭连接
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    System.out.println(e);
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    System.out.println(e);
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    System.out.println(e);
                }
            }
        }
    }
}
